package com.cn.bukeManage.service.realm;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cn.bukeManage.pojo.Resource;
import com.cn.bukeManage.pojo.Role;
import com.cn.bukeManage.pojo.User;
import com.cn.bukeManage.service.UserService;

@Service
public class AuthRealm extends AuthorizingRealm {
	@Autowired
	private UserService userService;

	@Override
	public String getName() {
		return getClass().getName() + "-" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
	}

	

	/**
	 * 登录完成后，当页面上遇到shiro标签后将会调用myrealm中的AuthorizationInfo方法，获得当前登录人的具体权限
	 * 如果当前登录用户拥有权限标签中书写的权限，则内容显示，否则不显示。
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		// 获取当前用户
		SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
		User user = (User) super.getAvailablePrincipal(principals);
		if (user == null) {
			throw new AccountException("帐号或密码不正确");
		}else {
			Set<Role> roleList = userService.getRoles(user.getUserId());
//		Set<Resource> resourceList = userService.getResources(user.getUserId());
			if (roleList != null && roleList.size() > 0) {
				for (Role role : roleList) {
					if (role.getRoleName() != null) {
						simpleAuthorInfo.addRole(role.getRoleName());
					}
				}
			}
//			if (resourceList != null && resourceList.size() > 0) {
//				for (Resource resource : resourceList) {
//					if (resource.getName() != null) {
//						simpleAuthorInfo.addStringPermission(resource.getName());
//					}
//				}
//			}
		}
		return simpleAuthorInfo;
	}


	
	/**
	 * 当用户登录触发过滤器将会调用自定义myrealm中的AuthenticationInfo查询根据自己写的方法查询是否允许登录
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		// TODO Auto-generated method stub
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String userName = token.getUsername();
		String password = String.valueOf(token.getPassword());
		User user = userService.checkUser(userName, password);
		if (user != null) {
			if (user.getUseable() != null && "0".equals(user.getUseable())) {
				throw new DisabledAccountException("帐号已被禁用");
			}
			this.setSession("userId", user.getUserId());
			this.setSession("nikeName", user.getNikeName());
			return new SimpleAuthenticationInfo(user, token.getPassword(), getName());
		} else {
			throw new AccountException("帐号或密码不正确");
		}
	}

	/**
	 * 获取session
	 * @return
	 */
	private Session getSession() {
		try {
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session == null) {
				session = subject.getSession();
			}
			if (session != null) {
				return session;
			}
		} catch (InvalidSessionException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 保存登录名
	 */
	private void setSession(Object key, Object value) {
		Session session = getSession();
		System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
		if (null != session) {
			session.setAttribute(key, value);
		}
	}
}
